package psn.polaris.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import psn.polaris.util.SpringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Component
public class PolarisStarterEventListener implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(PolarisStarterEventListener.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 向Spring工具注册上下文
        SpringUtils.registerContext(event.getApplicationContext());
        // 获取全部初始化执行器
        List<AbsPolarisStartProcess> startProcessList = SpringUtils.getSpringBeanByType(AbsPolarisStartProcess.class);
        startProcessList.sort(new Comparator<AbsPolarisStartProcess>() {
            @Override
            public int compare(AbsPolarisStartProcess o1, AbsPolarisStartProcess o2) {
                return o1.getOrderNum() - o2.getOrderNum();
            }
        });
        for (AbsPolarisStartProcess absPolarisStartProcess : startProcessList) {
            absPolarisStartProcess.processInit();
        }
        logger.info("初始化器执行完成");
    }

}
